<template>
  <div class="bg-[#fff] pt-[20px]">
    <div class="px-[10px]">
      <el-form :model="form" :inline="true" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="昵称">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="py-[20px] px-[10px] bg-[#F5F5F5]">
      <el-button type="primary" @click="handleAdd">新增员工</el-button>
    </div>
    <div>
      <div v-if="selectedManagerId">
        <div class="mb-[10px] px-[10px] font-bold">当前管理领导: {{ selectedManagerName }}</div>
        <el-table :data="tableData" style="width: 100%" border height="calc(100vh - 260px)" v-loading="loading">
          <el-table-column label="序号" width="80" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="username" label="用户名" width="150" />
          <el-table-column prop="nickname" label="昵称" width="150" />
          <el-table-column prop="email" label="电子邮箱" width="200" />
          <el-table-column prop="phone" label="手机号" width="150" />
          <el-table-column prop="gender" label="性别" width="100">
            <template #default="scope">
              {{ scope.row.gender === 1 ? '男' : '女' }}
            </template>
          </el-table-column>
          <el-table-column prop="salary" label="底薪" width="100" />
          <el-table-column prop="avatar" label="头像" width="100">
            <template #default="scope">
              <el-image :src="scope.row.avatar" v-if="scope.row.avatar" :preview-src-list="[scope.row.avatar]" />
              <span v-else>暂无</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-wrap p-[10px]">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[20, 50, 100, 200]"
            :disabled="disabled" layout="total, sizes, prev, pager, next, jumper" :total="total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
      <div v-else class="text-center py-[50px] text-gray-500">
        请在左侧选择一位领导
      </div>
    </div>

    <!-- 新增编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="40%" :before-close="handleCancel">
      <el-form :model="dialogForm" ref="dialogFormRef" label-width="120px">
        <el-form-item label="用户名" prop="username" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
          <el-input v-model="dialogForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname" :rules="[{ required: true, message: '请输入昵称', trigger: 'blur' }]">
          <el-input v-model="dialogForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="密码" v-if="dialogType === 'add'" prop="password" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
          <el-input v-model="dialogForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email" :rules="[
          { required: true, message: '请输入电子邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的电子邮箱格式', trigger: ['blur', 'change'] }
        ]">
          <el-input v-model="dialogForm.email" placeholder="请输入电子邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone" :rules="[
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: ['blur', 'change'] }
        ]">
          <el-input v-model="dialogForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender" :rules="[{ required: true, message: '请选择性别', trigger: 'change' }]">
          <el-select v-model="dialogForm.gender" placeholder="请选择性别">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="底薪" prop="salary" :rules="[
          { required: true, message: '请输入底薪', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: ['blur', 'change'] }
        ]">
          <el-input v-model.number="dialogForm.salary" placeholder="请输入底薪" />
        </el-form-item>
        <el-form-item label="上级领导" prop="managerId" :rules="[{ required: true, message: '请选择上级领导', trigger: 'change' }]">
          <el-select v-model="dialogForm.managerId" placeholder="请选择上级领导">
            <el-option v-for="manager in managers" :key="manager.id" :label="manager.name" :value="manager.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :http-request="handleAvatarUpload"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="dialogForm.avatar" :src="dialogForm.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, watch, onMounted } from 'vue';
import { get, post } from '@/request';
import { vToast } from '@/plugins/vToast';
import { vConfirm } from '@/plugins/vConfirm';

// 接收父组件传递的选中领导信息
const props = defineProps({
  selectedManagerId: {
    type: [String, Number, null],
    default: null
  },
  selectedManagerName: {
    type: String,
    default: ''
  }
});

// 表单相关
const form = reactive({
  username: '',
  nickname: ''
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(20);
const disabled = ref(false);
const total = ref(0);
const loading = ref(false);
const tableData = reactive([]);

// 领导列表
const managers = ref([]);

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const dialogType = ref(''); // 'add' 或 'edit'
const dialogForm = reactive({
  id: '',
  username: '',
  nickname: '',
  password: '',
  email: '',
  phone: '',
  gender: 1,
  salary: 0,
  managerId: '',
  avatar: ''
});
const dialogFormRef = ref(null);

// 搜索功能
const search = () => {
  currentPage.value = 1;
  loadEmployeeData();
};

// 加载员工数据
const loadEmployeeData = async () => {
  if (!props.selectedManagerId) return;
  
  loading.value = true;
  try {
    const params = {
      username: form.username,
      nickname: form.nickname,
      managerId: props.selectedManagerId,
      page: currentPage.value,
      pageSize: pageSize.value
    };

    const res = await get('/employee/list', params);
    if (res && res.code === 200) {
      tableData.length = 0;
      res.data?.list?.forEach(item => {
        tableData.push(item);
      });
      total.value = res.data?.pagination?.total || 0;
    }
  } catch (error) {
    console.error('获取员工列表失败:', error);
    vToast({ message: '获取员工列表失败' });
  } finally {
    loading.value = false;
  }
};

// 加载领导列表
const loadManagers = async () => {
  try {
    const res = await get('/dict/list');
    if (res && res.code === 200) {
      managers.value = res.data?.list || [];
    }
  } catch (error) {
    console.error('获取领导列表失败:', error);
    vToast({ message: '获取领导列表失败' });
  }
};

// 新增员工
const handleAdd = () => {
  try {
    dialogType.value = 'add';
    dialogTitle.value = '新增员工';
    // 清空表单
    Object.assign(dialogForm, {
      id: '',
      username: '',
      nickname: '',
      password: '',
      email: '',
      phone: '',
      gender: 1,
      salary: 0,
      managerId: props.selectedManagerId,
      avatar: ''
    });
    // 重置表单验证
    if (dialogFormRef.value) {
      dialogFormRef.value.resetFields();
    }
    dialogVisible.value = true;
  } catch (error) {
    console.error('打开新增表单失败:', error);
    vToast({ message: '打开新增表单失败' });
  }
};

// 编辑员工
const handleEdit = (row) => {
  try {
    dialogType.value = 'edit';
    dialogTitle.value = '编辑员工';
    // 填充表单数据
    Object.assign(dialogForm, {
      id: row.id,
      username: row.username,
      nickname: row.nickname,
      password: '', // 编辑时不显示密码
      email: row.email,
      phone: row.phone,
      gender: row.gender,
      salary: row.salary,
      managerId: row.managerId,
      avatar: row.avatar
    });
    dialogVisible.value = true;
  } catch (error) {
    console.error('打开编辑表单失败:', error);
    vToast({ message: '打开编辑表单失败' });
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!dialogFormRef.value) return;

  try {
    await dialogFormRef.value.validate();

    // 准备提交数据
    const params = {
      username: dialogForm.username,
      nickname: dialogForm.nickname,
      email: dialogForm.email,
      phone: dialogForm.phone,
      gender: dialogForm.gender,
      salary: dialogForm.salary,
      managerId: dialogForm.managerId,
      avatar: dialogForm.avatar
    };

    // 新增时需要密码
    if (dialogType.value === 'add') {
      params.password = dialogForm.password;
    }

    // 编辑时需要id
    if (dialogType.value === 'edit') {
      params.id = dialogForm.id;
    }

    // 调用接口
    const response = dialogType.value === 'add'
      ? await post('/employee/create', params)
      : await post('/employee/update', params);

    if (response.code === 200) {
      vToast({ message: dialogType.value === 'add' ? '新增员工成功' : '编辑员工成功' });
      dialogVisible.value = false;
      loadEmployeeData();
    } else {
      vToast({ message: response.msg || (dialogType.value === 'add' ? '新增员工失败' : '编辑员工失败') });
    }
  } catch (error) {
    if (error === false) {
      // 表单验证失败
      return;
    }
    console.error(dialogType.value === 'add' ? '新增员工失败:' : '编辑员工失败:', error);
    vToast({ message: dialogType.value === 'add' ? '新增员工失败' : '编辑员工失败' });
  }
};

// 取消表单
const handleCancel = () => {
  dialogVisible.value = false;
  // 清空表单
  if (dialogFormRef.value) {
    dialogFormRef.value.resetFields();
  }
};

// 删除员工
const handleDelete = (row) => {
  vConfirm({ message: `确定删除员工 ${row.username} 吗？` })
    .then(async () => {
      try {
        const response = await post('/employee/delete', { id: row.id });
        if (response.code === 200) {
          vToast({ message: '删除成功' });
          loadEmployeeData();
        } else {
          vToast({ message: response.msg || '删除失败' });
        }
      } catch (error) {
        console.error('删除员工失败:', error);
        vToast({ message: '删除失败' });
      }
    })
    .catch(() => { });
};

// 头像上传处理
const handleAvatarUpload = async (options) => {
  try {
    const formData = new FormData();
    formData.append('file', options.file);
    
    const response = await post('/upload', formData);
    if (response.code === 200) {
      dialogForm.avatar = response.data.url;
      vToast({ message: '上传成功' });
    } else {
      vToast({ message: response.msg || '上传失败' });
    }
  } catch (error) {
    console.error('上传头像失败:', error);
    vToast({ message: '上传失败' });
  }
};

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    vToast({ message: '上传头像图片只能是 JPG/PNG 格式!' });
  }
  if (!isLt2M) {
    vToast({ message: '上传头像图片大小不能超过 2MB!' });
  }
  return isJPG && isLt2M;
};

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size;
  loadEmployeeData();
};

const handleCurrentChange = (current) => {
  currentPage.value = current;
  loadEmployeeData();
};

// 监听选中的领导变化
watch(() => props.selectedManagerId, (newVal) => {
  if (newVal) {
    // 加载该领导的员工数据
    loadEmployeeData();
  }
});

// 初始化
onMounted(() => {
  loadManagers();
  
  // 模拟从left.vue获取选中的领导ID
  // 实际项目中应该通过props或状态管理获取
  // 这里为了演示，先设置一个默认值
  // selectedManagerId.value = '1';
});
</script>

<style lang="less" scoped>
.dict-page {
  box-sizing: border-box;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: inline-block;
  width: 100px;
  height: 100px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
